<template>
  <div class="min-h-screen p-4 min-w-full">
    <el-dialog
      title="pdf预览( 若无展示，请确认申报内容有所保存 )"
      :visible.sync="showPdf"
      width="80%"
    >
      <iframe
        :src="'/pdf/web/viewer.html?file=' + pdfUrl"
        frameborder="1"
        height="800"
        width="100%"
        style="margin-top: 0.25rem"
      ></iframe>
    </el-dialog>
    <div
      class="
        flex flex-wrap
        content-center
        rounded-sm
        border
        px-2
        pt-2
        bg-white
        overflow-hidden
      "
    >
      <div
        v-for="(item, index) in headList"
        :key="item.id"
        :class="[
          'tag',
          index == activeTabIndex ? 'bg-blue-500 text-white' : '',
        ]"
        @click="handleTabClick(index)"
      >
        {{ item.name }}
      </div>

      <div class="btn bg-blue-400 hover:bg-blue-500" @click="previewPDFFile">
        申报预览并打印
      </div>

      <el-button
        class="btn bg-green-400 hover:bg-green-500 hover:text-white text-base"
        :disabled="!isCanSubmit"
        @click="beforeSubmit"
      >
        提交申报
      </el-button>
    </div>

    <div v-show="activeTabIndex == 0" class="bg-white overflow-hidden">
      <div class="text-center text-xl border-b p-3 mt-4">
        {{ themeName == "unicorn" ? "独角兽企业" : "瞪羚企业" }}
        申报说明
      </div>

      <div class="p-8 px-10">
        <!-- <div class="font-bold">申报指南</div> -->
        <div
          v-if="guide.content"
          style="min-height: 400px"
          v-html="guide.content"
        ></div>
        <div v-else style="min-height: 400px; padding: 20px 0">详见附件</div>

        <div class="py-4" v-if="guide.fileList && guide.fileList.length > 0">
          <div class="text-base font-bold py-4">附件</div>
          <a
            class="
              block
              text-base text-blue-500
              hover:text-blue-400
              cursor-pointe
              alink
            "
            v-for="item in guide.fileList"
            :key="item.pathName"
            :href="addUrlhead(item.pathName)"
            target="_blank"
          >
            {{ item.fileName }}
          </a>
        </div>
        <div style="display: flex; justify-content: flex-end">
          <DeclareNextItem />
        </div>
      </div>
    </div>
    <div v-show="activeTabIndex == 1">
      <EnterpriseInfoForm
        ref="infoForm"
        :sourceList.sync="declareCompany"
        :isSubmit="isCanSubmit"
      />
    </div>
    <div v-show="activeTabIndex == 2">
      <EnterpriseStaffForm ref="staffForm" :isSubmit="isCanSubmit" />
    </div>
    <div v-show="activeTabIndex == 3">
      <EnterpriseEconomicForm
        ref="economicForm"
        :sourceList="declareEconomicsDataList"
        :isSubmit="isCanSubmit"
      />
    </div>
    <div v-show="activeTabIndex == 4">
      <EnterpriseFinancForm
        ref="financForm"
        :sourceList="declareCompanyFinancingList"
        :isSubmit="isCanSubmit"
      />
    </div>
    <div v-show="activeTabIndex == 5">
      <RelateEnterpriseForm
        ref="enterpriseForm"
        :sourceList="declareRelationCompanyList"
        :isSubmit="isCanSubmit"
        @checkFormNumberV="checkFormNumberV"
      />
    </div>
    <div v-show="activeTabIndex == 6">
      <AdvantageForm
        ref="advantageForm"
        :sourceList="declareContrast"
        :isSubmit="isCanSubmit"
      />
    </div>

    <div v-show="activeTabIndex == 7">
      <InnvoateForm
        ref="innvoateForm"
        :sourceList="declareInnovateList"
        :isSubmit="isCanSubmit"
      />
    </div>

    <div v-show="activeTabIndex == 8">
      <BuildForm
        ref="buildForm"
        :sourceList="declareBuildList"
        :isSubmit="isCanSubmit"
      />
    </div>

    <div v-show="activeTabIndex == 9">
      <HonorForm
        ref="honorForm"
        :sourceList="declareQualificationsList"
        :isSubmit="isCanSubmit"
      />
    </div>
    <div v-show="activeTabIndex == 10">
      <PlanForm
        ref="planForm"
        @checkFormNumberV="checkFormNumberV"
        :sourceObj="declarePlan"
        :isSubmit="isCanSubmit"
      />
    </div>
    <div v-show="activeTabIndex == 11">
      <EnclosureForm
        ref="enclosureForm"
        @checkFormNumberV="checkFormNumberV"
        :isSubmit="isCanSubmit"
      />
    </div>

    <!-- 提交前的确认dialog -->
    <el-dialog
      title="提交确认"
      :visible.sync="showConfirm"
      width="30%"
      class="submit-dialog"
    >
      <el-result
        icon="success"
        title="是否确认提交申报？提交后申报不可再编辑！"
        subTitle="注：申报信息填写越完善，越有助于申报认定"
      >
        <template slot="extra">
          <el-button @click="showConfirm = false"> 继续完善 </el-button>
          <el-button type="primary" @click="submitDeclare">确认提交</el-button>
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script>
import EnterpriseInfoForm from "./EnterpriseInfoForm.vue";
import EnterpriseStaffForm from "./EnterpriseStaffForm.vue";
import EnterpriseEconomicForm from "./EnterpriseEconomicForm.vue";
import EnterpriseFinancForm from "./EnterpriseFinancForm.vue";
import RelateEnterpriseForm from "./RelateEnterpriseForm.vue";
import AdvantageForm from "./AdvantageForm.vue";
import InnvoateForm from "./InnvoateForm.vue";
import BuildForm from "./BuildForm.vue";
import HonorForm from "./HonorForm.vue";
import PlanForm from "./PlanForm.vue";
import EnclosureForm from "./EnclosureForm.vue";

import { getDeclareDetail } from "@/api/declareForm/getDetail";
import { getInfo as getPolicyDeclare } from "@/api/policyDeclare/";
import { uploadFileList } from "@/api/declareForm";
export default {
  name: "enterpriseForm",
  props: {},
  components: {
    EnterpriseInfoForm,
    EnterpriseStaffForm,
    EnterpriseEconomicForm,
    EnterpriseFinancForm,
    RelateEnterpriseForm,
    AdvantageForm,
    InnvoateForm,
    BuildForm,
    HonorForm,
    PlanForm,
    EnclosureForm,
  },
  computed: {
    themeName() {
      let typeId = this.$route.query.typeId;
      if (typeId == 0 || typeId == 1) {
        return "gazelle";
      }
      if (typeId == 2 || typeId == 3 || typeId == 4) {
        return "unicorn";
      }
      return "";
    },
    // 添加url头
    addUrlhead() {
      return (url) => {
        return process.env.VUE_APP_BASE_API + "/file/" + url;
      };
    },
  },
  data() {
    return {
      refFormList: [
        "infoForm",
        "staffForm",
        "economicForm",
        "financForm",
        "enterpriseForm",
        "advantageForm",
        "innvoateForm",
        "buildForm",
        "honorForm",
        "planForm",
        "enclosureForm",
      ],
      submitLoading: false,
      pdfUrl: "",
      pdfPath: "",
      showPdf: false,
      baseUrl: process.env.VUE_APP_BASE_API,

      // themeUpload: 'unicorn',
      relationId: "",
      activeTabIndex: 0,
      headList: [
        { id: 0, name: "申报说明" },
        { id: 1, name: "企业信息" },
        { id: 2, name: "企业人员信息" },
        { id: 3, name: "企业发展经济数据信息" },
        { id: 4, name: "企业融资经历" },
        { id: 5, name: "关联企业信息" },
        { id: 6, name: "企业行业地位及对比竞争优势" },
        { id: 7, name: "企业技术创新信息" },
        { id: 8, name: "企业产学研建设信息" },
        { id: 9, name: "企业荣誉与资质情况" },
        { id: 10, name: "企业未来3年发展规划" },
        { id: 11, name: "附件" },
      ],

      // 打开提交确认dialog
      showConfirm: false,
      // 当前申报是否可提交
      isCanSubmit: false,

      guide: {
        content: ``,
        fileList: [],
      },

      // 企业荣誉与资质情况
      declareQualificationsList: [],

      // 企业产学研建设信息
      declareBuildList: [],

      // 企业信息
      declareCompany: {},

      // 企业发展经济数据信息
      declareEconomicsDataList: [],

      // 企业融资经历
      declareCompanyFinancingList: [],

      // 关联企业
      declareRelationCompanyList: [],

      //  企业行业地位及对比竞争优势
      declareContrast: {},

      // 企业技术创新信息
      declareInnovateList: [],

      // 企业未来3年发展规划
      declarePlan: {},
    };
  },
  watch: {
    "$route.query.declareIndex": {
      handler(v, oldv) {
        this.initDeclareIndex(v);
      },
      deep: true,
    },
    $route: {
      handler(v, oldv) {
        document.querySelector(".right").scrollTop = 0;
      },
      deep: true,
    },
  },
  created() {
    // 获取申报说明
    this.getDeclareExplain();
    this.initRelationId();
    this.initFormContent();
  },
  mounted() {
    this.$nextTick(() => {
      this.initDeclareIndex();
      // 获取保存的申报政策文案和附件列表
      this.guide.content = sessionStorage.getItem("policyContent");
      this.guide.fileList = sessionStorage.getItem("policyFileList")
        ? JSON.parse(sessionStorage.getItem("policyFileList"))
        : [];
    });
  },
  methods: {
    initDeclareIndex(declareIndexArg) {
      let declareIndex = 0;
      if (declareIndexArg || declareIndexArg == 0) {
        declareIndex = declareIndexArg;
      } else {
        declareIndex = this.$route.query.declareIndex;
      }
      if (
        isNaN(declareIndex) ||
        declareIndex < 0 ||
        declareIndex > this.headList.length - 1
      ) {
        this.handleTabClick(0);
        return false;
      }
      this.activeTabIndex = declareIndex;
    },

    async previewPDFFile() {
      await this.initFormContent();
      let url = this.pdfPath;
      if (!url) {
        this.$message({
          type: "error",
          message: "您还未保存过任何信息",
        });
        return;
      }
      // this.pdfUrl = 'http://' + window.location.host + process.env.VUE_APP_BASE_API + '/file/' + url
      this.showPdf = true;
      this.pdfUrl =
        "http://" +
        window.location.host +
        process.env.VUE_APP_BASE_API +
        "/file/" +
        url;

      // window.open("https://view.officeapps.live.com/op/view.aspx?src=" + url);
    },
    previewFile(url) {
      window.open("https://view.officeapps.live.com/op/view.aspx?src=" + url);
    },

    initFormContent() {
      let id = this.$route.query.id;
      return getDeclareDetail(id).then((res) => {
        if (res.code == 200) {
          if (res.data && res.data.pdfFilePath) {
            this.pdfPath = res.data.pdfFilePath;
          }
          this.distriFormContent(res.data);
          if (res.data.declareType == 0) {
            this.isCanSubmit = true;
          } else {
            if (res.data.status == 3) {
              this.isCanSubmit = true;
            } else {
              this.isCanSubmit = false;
            }
          }
        }
      });
    },
    distriFormContent(resObj) {
      if (resObj) {
        if (resObj["declareQualificationsList"]) {
          this.declareQualificationsList = resObj["declareQualificationsList"];
        }
        if (resObj["declareBuildList"]) {
          this.declareBuildList = resObj["declareBuildList"];
        }
        if (resObj["declarePlan"]) {
          this.declarePlan = resObj["declarePlan"];
        }
        if (resObj["declareCompany"]) {
          this.declareCompany = resObj["declareCompany"];
        }
        if (resObj["declareEconomicsDataList"]) {
          this.declareEconomicsDataList = resObj["declareEconomicsDataList"];
        }
        if (resObj["declareCompanyFinancingList"]) {
          this.declareCompanyFinancingList =
            resObj["declareCompanyFinancingList"];
        }
        if (resObj["declareRelationCompanyList"]) {
          this.declareRelationCompanyList =
            resObj["declareRelationCompanyList"];
        }

        if (resObj["declareContrast"]) {
          this.declareContrast = resObj["declareContrast"];
        }
        if (resObj["declareInnovateList"]) {
          this.declareInnovateList = resObj["declareInnovateList"];
        }
      }
    },

    initRelationId() {
      let realationId = this.$route.query.typeId;
      if (realationId) {
        this.relationId = realationId;
      }
    },

    // 根据返回的policyId获取对应的申报说明
    getDeclareExplain() {
      let policyId = this.$route.query.policyId;
      if (policyId) {
        getPolicyDeclare(policyId).then((res) => {
          if (res.code == 200) {
            this.guide.content = res.data.policyContent;
            this.guide.fileList = res.data.fileList;
            sessionStorage.setItem("policyContent", res.data.policyContent);
            sessionStorage.setItem(
              "policyFileList",
              JSON.stringify(res.data.fileList)
            );
          }
        });
      }
    },

    handleTabClick(index) {
      // this.activeTabIndex = index;
      let id = this.$route.query.id;
      let typeId = this.$route.query.typeId;
      let policyId = parseInt(this.$route.query.policyId);
      this.$router.replace({
        path: "/user/enterprise/form",
        query: { id, typeId, declareIndex: index, policyId },
      });
    },

    // 表单校验数字使用
    checkFormNumberV(rule, value, callback) {
      if (!value && value !== "0.00" && value !== 0) {
        // return callback(new Error("该项不能为空"));
        return callback();
      }
      if (value < 0) {
        return callback(new Error("请输入有效数值"));
      }
      return callback();
    },
    // 校验其他表单是否成功上传

    // 提交前打开确认dialog
    beforeSubmit() {
      this.showConfirm = true;
    },
    // 提交
    async submitDeclare() {
      // 确实是否提交
      if (!this.isCanSubmit) {
        this.$message({
          type: "error",
          message: "该申报已经提交，不能再次提交",
        });
        return;
      } else {
        // 关闭提示框
        this.showConfirm = false;

        if (this.submitLoading) {
          return;
        }
        this.submitLoading = true;

        // 企业信息表
        let infoFormRes = await this.$refs["infoForm"]["submitForm"]();
        let enclosureFormRes = await this.$refs["enclosureForm"][
          "submitForm"
        ]();

        let nowFormIndex = parseInt(this.$route.query["declareIndex"]);
        const infoFormIndex = 1;
        const enclosureFormIndex = 11;

        if (!infoFormRes) {
          // 跳转至企业基本信息表单页面
          // 判断是否为  企业基本信息页面
          if (nowFormIndex !== infoFormIndex) {
            this.handleTabClick(infoFormIndex);
          }
          this.submitLoading = false;
          return;
        }

        if (!enclosureFormRes) {
          // 跳转至 附件表单页面
          // 判断是否为 附件表单页面
          if (nowFormIndex !== enclosureFormIndex) {
            this.handleTabClick(enclosureFormIndex);
          }
          this.submitLoading = false;
          return;
        }

        let id = this.$route.query.id;
        if (!id) {
          this.submitLoading = false;
          return;
        }

        uploadFileList(id).then((res) => {
          this.submitLoading = false;
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "提交申报成功",
            });
            this.isCanSubmit = false;
            this.$router.push({ path: "/user/declare" });
          }
        });
      }
    },
  },
};
</script>

<style lang="scss">
.tag {
  @apply py-2 cursor-pointer px-4 mr-4 mb-2 rounded-md border;

  &:hover {
    @apply bg-blue-400 text-white;
  }
}

.fixed-input-w {
  ::v-deep input {
    @apply w-96;
  }
}

.form-title {
  @apply text-center text-xl border-b p-3 mt-4;
}

.form-sub-title {
  @apply p-2 px-0 mt-4 mb-8 text-xl border-b border-dashed border-gray-400;

  &:first-child {
    @apply mt-0;
  }
}

.submit-dialog {
  /** 调整el-dialog__body的顶距 */
  .el-dialog__body {
    padding-top: 0 !important;
  }
}

/** 通用label样式 */
.m-label {
  font-weight: bold;
  vertical-align: middle;
  font-size: 14px;
  color: #606266;
}
</style>
